<template>
  <div>
    <BreakSpace label="出卖人信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="sellerInfo"
      :list="initFormSeller"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleSeller"
    />
    <BreakSpace label="买受人信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="buyerInfo"
      :list="initFormBuyer"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleBuyer"
    />
    <BreakSpace label="合同信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="contractInfo"
      :list="initFormContract"
      :cols="3"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleContract"
    />
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="fileInfo"
      :list="initFormFile"
      :cols="1"
      :labelWidth="140"
      :isSubmitBtn="false"
      :formType="infoBasic"
      @formChange="formChangeHandleFile"
    />
    <!-- table -->
    <BreakSpace label="车辆信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      height='300'
      ref="table"
      :columns="columns"
      :dataSource="dataSource"
      :isColumnFilter="false"
      :datakey="'dealerName'"
      :isToperInfo="false"
      columnsRef='customerManage_filingManage_contractRegister_addDialog_01'
      :onCellChange="onCellChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" v-if="infoBasic != 'show'" @click="productHandle">选择车辆</el-button>
      </template>
    </FilterTable>
    <div class="dialogBottmView" >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button @click="saveDialog" :loading="saveLoading" v-if="infoBasic != 'show'" type="primary">{{ btnText }}</el-button>
    </div>
    <!-- 项目信息弹窗 -->
    <BaseDialog 
      title="项目选择" 
      width="1000px"
      destroyOnClose
      :visible.sync="visibleProject"
      :containerStyle="{height: '390px', overflow: 'auto', paddingBottom: '60px'}" >
      <project-madal  ref="projectDialog" :projectStatus="this.approvalManageType.PROJECT_STATUS_CHIEF_INSPECTOR_REVIEW" selectType='single'  @close="closeProject" />
   </BaseDialog>
    <!-- 车辆信息弹窗 -->
    <BaseDialog 
      title="车辆选择" 
      width="1000px"
      destroyOnClose
      :visible.sync="visibleProduct"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
      <product-madal selectType='multiple' ref="productDialog" @close="closeProduct" />
   </BaseDialog>
   <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-madal  ref='addDialogRef' selectType='single' v-model="initDealerData"  @close="closeDealer" />
    </BaseDialog>
  </div>
</template>
<script>
// import personnelMadal from '@/pages/cms-common/user'
import {formatdateByTime, formatdateByDay } from '@/utils/index';
import projectMadal from '@/pages/cms-pages/customerManage/approvalManage/inquire/contractRegisterSelectList'
import productMadal from '@/pages/cms-common/product'
import dealerMadal from '@/pages/cms-common/dealerdata'
import { dictionary } from '@/utils/dictMixin';
import { insertContract ,updataContract ,searchDetailListByContractId  } from '@/api/cms-api/customerManage/filingManage/contractRegister';
import * as approvalManageType from '@/api/cms-api/customerManage/approvalManage/types';
import * as types from '@/api/cms-api/customerManage/filingManage/contractRegister/types';

export default {
  components: {
    projectMadal,dealerMadal,productMadal
  },
  props: {
    value:{
        type: Object,
        default: null
    }
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    return {
      contractId:"",  //合同ID，修改时进入赋值
      projectId:"",   //项目ID
      editRow:{},     //车辆信息列表编辑行号
      saveLoading: false,
      formData:[],
      dealerList:[],
      productList:[],
      visibleProject: false,
      visibleProduct: false,
      visibleDealer: false,
      initDealerData:{},
      initProjectData:{},
      dataSource:[],
      isSelectColumn: false,
      infoBasic:this.value.type,
      initFormSeller: this.initFormSellerFun(),
      initFormBuyer: this.initFormBuyerFun(),
      initFormContract: this.initFormContractFun(),
      initFormFile: this.initFormFileFun(),
      columns: this.creatHeader(),
      approvalManageType:approvalManageType,
      dealerSelect:true,
    };
  },
  mounted() {
    //如果传入参数不为空，则说明是修改进入，初始化对应数据
    if(this.value!=null && (this.value.type=="edit"||this.value.type=="show")){
      this.init();
    }
    
  },
  computed: {
    //根据传入参数，确定底部按钮名称
    btnText() {
      return this.conf[this.value.type];
    }
  },
  methods: {
    //修改时，初始化页面数据
    async init(){
      // 更新接口需要的记录 ID
      this.contractId = this.value.rowData.contractId;
      this.projectId = this.value.rowData.projectId;
      //循环为表单赋值
      this.initFormSeller.forEach(x => {
        x.initialValue = this.value.rowData[x.fieldName];
      });
      this.initFormBuyer.forEach(x => {
        x.initialValue = this.value.rowData[x.fieldName];
      });
      this.initFormContract.forEach(x => {
        if(x.fieldName=="contractPrice"){
          x.initialValue = parseFloat(this.value.rowData[x.fieldName]);
        }else if(x.fieldName=="contractStartDate"){ //合同生效日期
          x.initialValue =  formatdateByTime(new Date(this.value.rowData[x.fieldName]));
        }else if(x.fieldName=="totalNum"){
          x.initialValue = this.value.rowData[x.fieldName];
        }else if(x.fieldName=="transportType"){
          x.initialValue = this.value.rowData[x.fieldName];
          //如果为代交车,则需选取代交经销商
        if(this.value.rowData[x.fieldName] == types.TRANSPORT_TYPE_REPLACE){
          this.dealerSelect = false;
        //如果不是代交车，则默认为当前经销商
        }else{
          this.dealerSelect = true;
        }
        }else{
          x.initialValue = this.value.rowData[x.fieldName];
        }
      });
      //附件信息回显
      this.initFormFile.forEach(x => {
        let urlsList = this.value.rowData.urls;
        if(urlsList!=null && urlsList.length>0){
          let fileList = [];
          for(let i in urlsList){
              let fileName = { name: urlsList[i].fileName };
              let fileId = { url: urlsList[i].fileId };
              let f = Object.assign(fileName, fileId);
              fileList.push(f);
          }
          //x.initialValue = Object.assign({}, { fileUrl: fileList });
          x.initialValue = fileList;
        }
      });

      //回显车辆信息
      let res = await searchDetailListByContractId(Object.assign({},{contractId : this.contractId}));
     if (res.resultCode === 200) {
        //如果为明细页面 设置为不可编辑
        let columnActionIndex = null;
        if(this.infoBasic == 'show'){
          this.columns.forEach((x,index) =>{
            x.editable = false;

            if(x.dataIndex === 'column-action'){
							columnActionIndex = index;
            }
            if(x.dataIndex === 'dealerName'){
							delete x.render ;
            }

          });
          if(columnActionIndex != null){
            this.columns.splice(columnActionIndex,1);
          }
        }
        if(res.data && res.data.length>0){
          for(let i in res.data){
            //如果不为明细页面 增加输入框
            if(this.infoBasic != 'show'){
              res.data[i].contractNumIsEdit=true;  //增加输入框
              res.data[i].factorySinglePriceIsEdit=true;  //增加输入框
              res.data[i].stateSubsidyIsEdit=true;  //增加输入框
              res.data[i].localSubsidyIsEdit=true;  //增加输入框
              res.data[i].discountIsEdit=true;  //增加输入框
              res.data[i].actualSinglePriceIsEdit=true;  //增加输入框
              res.data[i].actualTotalPriceIsEdit=true;  //增加输入框
            }
  
            this.productList.push(res.data[i].materialId);
            // this.dataSource.push(Object.assign({},res.data[i]));
              
          }
          this.dataSource = Object.assign([],res.data);
        }

      }else {
        this.$notify.error({title: '提示信息',message:'获取车辆信息失败!'});
      }
    },
    //出卖人信息数据
    initFormSellerFun() {
      return [
         {
          type: 'INPUT',
          label: '出卖人（甲方）',
          fieldName: 'sellerName',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '住所',
          fieldName: 'sellerAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 200, 
              message: '长度最大200字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '授权代表人',
          fieldName: 'sellerAuthorizer',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },{
          type: 'INPUT',
          label: '联系人',
          fieldName: 'sellerContact',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '联系方式',
          fieldName: 'sellerMobile',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { 
              pattern: /^[1][3,4,5,7,8][0-9]{9}$/, 
              message: '请填写正确的手机格式', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '工作邮箱',
          fieldName: 'sellerEmail',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            },
            {
              type:'email',
              message: '请输入正确的邮箱', 
              trigger: 'change' 
            }
          ]
        }
      ];
    },
    //买受人信息数据
    initFormBuyerFun() {
      return [
         {
          type: 'INPUT',
          label: '买受人（乙方）',
          fieldName: 'buyerName',
          placeholder: '请输入',
          readonly: true,
          initialValue: '',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.projectHandle()}></el-button>;
          },
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '地址',
          fieldName: 'buyerAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 200, 
              message: '长度最大200字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '授权代表人',
          fieldName: 'buyerAuthorizer',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },{
          type: 'INPUT',
          label: '联系人',
          fieldName: 'buyerContact',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '联系方式',
          fieldName: 'buyerMobile',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { 
              pattern: /^[1][3,4,5,7,8][0-9]{9}$/, 
              message: '请填写正确的手机格式', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '工作邮箱',
          fieldName: 'buyerEmail',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 100, 
              message: '长度最大100字符', 
              trigger: 'change' 
            },
            {
              type:'email',
              message: '请输入正确的邮箱', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '项目名称',
          fieldName: 'projectName',
          placeholder: '请选择买受人',
          initialValue: '',
          disabled: true
        }
      ];
    },
    //合同信息数据
    initFormContractFun() {
      return [
         {
          type: 'INPUT',
          label: '合同名称',
          fieldName: 'contractName',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 200, 
              message: '长度最大200字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'INPUT',
          label: '合同编号',
          fieldName: 'contractNum',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 50, 
              message: '长度最大50字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accoutType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('2569'),
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'DATE',
          label: '合同生效日期',
          fieldName: 'contractStartDate',
          style: { width: '100%' },
          initialValue: '',
          readonly : true,
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'SELECT',
          label: '交车类型',
          fieldName: 'transportType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('2525'),
          change: val => {
            this.changeTransportType(val);
          },
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            }
          ]
        },
        {
          // type: 'INPUT_NUMBER',
          type: 'INPUT',
          label: '合同金额（含税）',
          fieldName: 'contractPrice',
          placeholder: '',
          precision:2,
          max:99999999.99,
          initialValue: 0,
          numberFormat:true,
          disabled:true,
          // rules: [
          //   {
          //     required: true,
          //     message: '必填',
          //     trigger: 'change'
          //   }
          // ]
        },
        {
          type: 'INPUT_NUMBER',
          label: '订购总数量',
          fieldName: 'totalNum',
          placeholder: '',
          precision:0,
          max:99999999,
          initialValue: 0,
          disabled:true,
          // rules: [
          //   {
          //     required: true,
          //     message: '必填',
          //     trigger: 'change'
          //   }
          // ]
        },
        {
          type: 'SELECT',
          label: '是否赠送充电桩',
          fieldName: 'isCharge',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('1004'),
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '收车地址',
          fieldName: 'receiveAddress',
          placeholder: '请输入',
          selfCols:2,
          initialValue: '',
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'change'
            },
            { max: 200, 
              message: '长度最大200字符', 
              trigger: 'change' 
            }
          ]
        },
        {
          type: 'TEXT_AREA',
          label: '特殊约定',
          fieldName: 'specialAgree',
          placeholder: '请输入',
          selfCols:3,
          initialValue: '',
          rules: [
            { max: 200, 
              message: '长度最大200字符', 
              trigger: 'change' 
            }
          ]
        }
      ];
    },
    //附件信息数据
    initFormFileFun() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          disabled: this.type === 'show' ? true : false,
          fieldName: 'fileUrl',
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload',
            fileTypes: ['jpg', 'png', 'pdf', 'doc', 'docx']
          }
        }
      ];
    },

    
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            let delBtn = "";
            if(this.infoBasic != 'show'){
              delBtn = <el-button size="mini"  type="text" onClick={() => this.editHandle(props.$index)}>删除</el-button>;
            }
            return (
              <div>
                {delBtn}
              </div>
            );
          }
        },
        { title: '交车经销商', dataIndex: 'dealerName', sorter: true,minWidth:'200', editable: false,
        render: props => { return <el-input placeholder="请选择" readonly={true} value={props.row.dealerName} ><el-button disabled={this.dealerSelect} onClick={() => this.dealerHandle(props.$index)}  slot="append" icon="el-icon-search" ></el-button></el-input>;}},
        { title: '品牌', dataIndex: 'brandName', sorter: true },
        { title: '车系', dataIndex: 'seriesName', sorter: true },
        { title: '车型', dataIndex: 'modelName', sorter: true },
        { title: '配置', dataIndex: 'packageName', sorter: true },
        { title: '内饰', dataIndex: 'trimColor', sorter: true },
        { title: '颜色', dataIndex: 'color', sorter: true },
        { title: '整车编码', dataIndex: 'productCode', sorter: true },
        { title: '商品名称', dataIndex: 'productName', sorter: true },
        { title: '生产厂商', dataIndex: 'manufacturer', sorter: true },
        { title: '产地', dataIndex: 'originPlace', sorter: true },
        { title: '数量', dataIndex: 'contractNum', sorter: true , editable: true, defaultEditable: true,  editType: 'number',editRequired:true,precision:0, min:0,max:99999999},
        { title: '出厂单价', dataIndex: 'factorySinglePrice',  sorter: true , editable: true, defaultEditable: true, editType: 'number' ,precision:2,min:0, max:99999999},
        { title: '国家补贴', dataIndex: 'stateSubsidy', sorter: true  , editable: true, defaultEditable: true, editType: 'number' ,precision:2, min:0,max:99999999},
        { title: '地方补贴', dataIndex: 'localSubsidy', sorter: true  , editable: true, defaultEditable: true, editType: 'number' ,precision:2,min:0, max:99999999},
        { title: '商务政策折让', dataIndex: 'discount', sorter: true  , editable: true, defaultEditable: true, editType: 'number',precision:2,min:0, max:99999999 },
        { title: '扣除补贴/价格折让后单价', dataIndex: 'actualSinglePrice', sorter: true  , editable: true, defaultEditable: true, editType: 'number',editRequired:true,precision:2,min:0, max:99999999 },
        { title: '扣除补贴/价格折让后总价', dataIndex: 'actualTotalPrice', sorter: true  , precision:2,min:0, max:99999999 ,numberFormat:true,}
      ];
    },
    //车辆信息表格内容变化
    onCellChange(keys, obj){
      let key = Object.keys(keys)[0];
      let a = key.substring(key.indexOf('|') + 1);
      console.log("obj:",obj);
      //扣除补贴/价格折让后总价 内容变化
      // if (a == 'actualTotalPrice') {
      //   this.countContractPrice();

      // }
      //扣除补贴/价格折让后单价 内容变化
      if (a == 'actualSinglePrice') {
        this.countContractPrice(obj);

      }
      //数量 内容变化
      if (a == 'contractNum') {
        this.countContractNum(obj);

      }
    },
    //动态计算合同金额（含税）
    // countContractPrice(){
    //   if(this.dataSource && this.dataSource.length>0){
    //     let totalPrice = 0;
    //     for(let i=0;i< this.dataSource.length;i++){
    //       totalPrice = (parseFloat( totalPrice) + parseFloat( this.dataSource[i].actualTotalPrice)).toFixed(2);
    //     }
    //     this.initFormContract.find(item => item.fieldName === 'contractPrice').initialValue = totalPrice;
    //   }
    // },

    // 内容变化 动态计算合同金额（含税）
    countContractPrice(obj){
      //如果数量不为空，扣除补贴/价格折让后单价不为空，则计算 扣除补贴/价格折让后总价
      if(obj.contractNum!=null  && obj.actualSinglePrice != null ){
        obj.actualTotalPrice = (parseFloat( obj.contractNum) * parseFloat( obj.actualSinglePrice)).toFixed(2);
      }

      if(this.dataSource && this.dataSource.length>0){
        let totalPrice = 0;
        for(let i=0;i< this.dataSource.length;i++){
          totalPrice = (parseFloat( totalPrice) + parseFloat( this.dataSource[i].actualTotalPrice)).toFixed(2);
        }
        this.initFormContract.find(item => item.fieldName === 'contractPrice').initialValue = totalPrice;
      }
    },
    //动态计算订购总数里
    countContractNum(obj){
      if(this.dataSource && this.dataSource.length>0){
        let totalNum = 0;
        for(let i=0;i< this.dataSource.length;i++){
          totalNum = parseInt( totalNum) + parseInt( this.dataSource[i].contractNum);
        }
        this.initFormContract.find(item => item.fieldName === 'totalNum').initialValue = totalNum;
      }

      this.countContractPrice(obj);
    },
    //交车类型切换
    changeTransportType(type) {
      if (type) {
        //清除已填的代交经销商
        if(this.dataSource && this.dataSource.length>0){
          for(let i=0;i< this.dataSource.length;i++){
            this.dataSource[i].dealerName='';
            this.dataSource[i].ownerCode='';
          }
        }
        //如果为代交车,则需选取代交经销商
        if(type == types.TRANSPORT_TYPE_REPLACE){
          this.dealerSelect = false;
          // this.columns.find(item => item.dataIndex === 'dealerName').disabled = false;
        //如果不是代交车，则默认为当前经销商
        }else{
          this.dealerSelect = true;
          // this.columns.find(item => item.dataIndex === 'dealerName').disabled = true;
        }
      }
    },
     // 项目信息 打开窗口
    projectHandle() {
      this.initPorjectData={
        excludeBigCustomer:true,//是否查询大客户经销商，如果查询 true，不查询 false
        id:1001
      }
      this.visibleProject = true;
    },
    // 项目信息 关闭窗口 -返回数据
    closeProject(data) {
      if(data&&data.data&&data.data.length>0){
        this.initFormBuyer[0].initialValue  = data.data[0].customerName;  //买受人（乙方）
        this.initFormBuyer[6].initialValue  = data.data[0].projectName; //项目名称
        this.projectId = data.data[0].projectId;    //项目ID
      }
      this.visibleProject = data.visible; //关闭弹窗
    },
    // 车辆信息 打开窗口
    productHandle() {
      this.visibleProduct = true;
    },
    // 车辆信息 关闭窗口 -返回数据
    closeProduct(data) {
      console.log("===data:",data);
      if(data.data&&data.data.length){
        for(let i=0;i<data.data.length;i++){
          let haveId = false;
          for(let j in this.productList){
             if(this.productList[j]==data.data[i].productId){
                haveId = true;
                // this.$notify.error({title: '提示信息',message:'此信息已存在!'});
                break;
             }
          }
          if(!haveId){
            this.productList.push(data.data[i].productId);  //存储物料id
            data.data[i].materialId=data.data[i].productId;
            data.data[i].dealerName="";
            // data.data[0].dealerNameIsEdit=true;
            data.data[i].subDealer="";
            data.data[i].ownerCode="";
            data.data[i].contractNum=undefined;
            data.data[i].contractNumIsEdit=true;  //增加输入框
            data.data[i].factorySinglePrice=undefined;
            data.data[i].factorySinglePriceIsEdit=true;  //增加输入框
            data.data[i].stateSubsidy=undefined;
            data.data[i].stateSubsidyIsEdit=true;  //增加输入框
            data.data[i].localSubsidy=undefined;
            data.data[i].localSubsidyIsEdit=true;  //增加输入框
            data.data[i].discount=undefined;
            data.data[i].discountIsEdit=true;  //增加输入框
            data.data[i].actualSinglePrice=undefined;
            data.data[i].actualSinglePriceIsEdit=true;  //增加输入框
            data.data[i].actualTotalPrice=0;
            data.data[i].actualTotalPriceIsEdit=true;  //增加输入框
            this.dataSource.push(Object.assign({},data.data[i]));
            
          }
        }

      }
      
      this.visibleProduct = data.visible; //关闭弹窗
    },
    // 经销商打开窗口 -传数据
    dealerHandle(index) {
      this.editRow = Object.assign({},{"index":index});
      this.initDealerData={
        excludeBigCustomer:true,//是否查询大客户经销商，如果查询 true，不查询 false
        id:1001
      }
      this.visibleDealer = true;
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      if(data&&data.data&&data.data.length>0){
        this.dataSource[this.editRow.index].dealerName = data.data[0].dealerName;
        this.dataSource[this.editRow.index].ownerCode = data.data[0].dealerCode;
      }
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //列表删除
    editHandle(index){
      this.$confirm('是否确定删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async() => {
            this.dataSource.splice(index,1);
            this.productList.splice(index,1);
				}).catch(() => {});
    },
 
    // 出卖人表单数据获取  
    formChangeHandleSeller(data){
      this.formData.seller = data;

      this.$refs.buyerInfo.SUBMIT_FORM();
    },
    // 买受人表单数据获取  
    formChangeHandleBuyer(data){
      this.formData.buyer = data;
      this.formData.buyer.projectId = this.projectId;
      this.$refs.contractInfo.SUBMIT_FORM();
    },
    // 合同信息表单数据获取  
    formChangeHandleContract(data){
      this.formData.contract = data;

      this.$refs.fileInfo.SUBMIT_FORM();
    },
    // 附件信息表单数据获取  
    formChangeHandleFile(data){
      this.formData.file = data;
      if(this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR() == null){
        this.saveLoading = true;
        this.doSave();
      }else{
        this.$notify.error({title: '提示信息',message:'车辆信息验证有误，请检查数据格式和必填项!'});
        
      }
    },
    
    //保存   
    saveDialog(){
      this.$refs.sellerInfo.SUBMIT_FORM();
    },
    async doSave(){
      //判断交车类型是否为代交车
      // let transportType = this.initFormContract.find(item => item.fieldName === 'transportType').initialValue;
      // //如果为代交车，则校验是否选择交车经销商
      // if(transportType == types.TRANSPORT_TYPE_REPLACE){
      //   if(this.dataSource && this.dataSource.length>0){
      //     for(let i=0;i< this.dataSource.length;i++){
      //        if(!this.dataSource[i].ownerCode){
      //          this.$notify.error({title: '提示信息',message:'请选择交车经销商!'});
      //          this.saveLoading = false;
      //          return;
      //        }
      //     }
      //   }
      // }

      let fileUrlList = [];
      for (let i = 0; i < this.formData.file.fileUrl.length; i++) {
        fileUrlList.push(Object.assign({},{"name":this.formData.file.fileUrl[i].name},{"url":this.formData.file.fileUrl[i].url}));
      }

      let submitData = Object.assign({}, this.value.rowData,this.formData.seller,this.formData.buyer,this.formData.contract);
      submitData.majorContractDetailDTOList = this.dataSource;
      submitData.filesInfo = fileUrlList;

      let res;
      //如果传入参数不为空并且为修改
      if(this.value!=null && this.value.type=="edit"){
        res = await updataContract(submitData,this.contractId);
      }else{
        res = await insertContract(submitData);
      }

      if (res.resultCode === 200) {
        this.$notify.success({title: '提示信息',message:'保存成功!'});
        // 重新加载
        this.closeDialog('refresh');
      }else {
        this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        this.closeDialog();
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false,type:type});
    }
  }
};
</script>

<style lang="less" scoped>
</style>
